import { useEffect, useRef, useState } from "react"

function useClock(domRef) {
    const [time, setTime] = useState("")
    const timerRef = useRef(-1)

    /* 组件挂载 开始计时 */
    useEffect(
        () => {
            timerRef.current = setInterval(() => {
                setTime(value => new Date().toLocaleTimeString())

                domRef && (domRef.current.innerHTML = new Date().toLocaleTimeString())
            }, 1000);
        },
        []
    )

    /* 组件卸载 取消定时器 */
    useEffect(
        () => () => clearInterval(timerRef.current),
        // () => {
        //     return () => {
        //         clearInterval(timerRef.current)
        //     }
        // },
        []
    )

    return time
}

function Son() {
    const time = useClock()
    return (
        <div>{time}</div>
    )
}

function Daughter() {
    const domRef = useRef(null)
    useClock(domRef)
    return (
        <div ref={domRef}>{"Daughter"}</div>
    )
}

export default function App(props) {
    return (
        <>
            <div>自定义hook之时钟</div>
            <Daughter />
            <Son />
        </>
    )
}